import { APIs } from '@/Http/http';
import { ElMessage } from 'element-plus';

/**
 * 上传图片工具函数
 * @param file 图片文件
 * @param uploadPath 上传路径（可选，默认为 /api/upload/image）
 * @returns Promise<string> 返回图片文件名（不是完整URL）
 */
export const uploadImage = async (file: File, uploadPath = '/api/upload/image'): Promise<string> => {
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await APIs.post(uploadPath, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    // 假设后端返回的是 { code: 200, data: "filename.png", message: "上传成功" }
    if (response.data.code === 200) {
      ElMessage.success('图片上传成功');
      return response.data.data; // 只返回文件名，如 "avatar_20231201_123456.png"
    } else {
      throw new Error(response.data.message || '上传失败');
    }
  } catch (error: any) {
    // console.error('图片上传失败:', error);
    ElMessage.error(error.message || '图片上传失败');
    throw error;
  }
};

/**
 * 批量上传图片
 * @param files 图片文件数组
 * @param uploadPath 上传路径
 * @returns Promise<string[]> 返回图片文件名数组
 */
export const uploadMultipleImages = async (files: File[], uploadPath = '/api/upload/images'): Promise<string[]> => {
  try {
    const formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });
    
    const response = await APIs.post(uploadPath, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success(`成功上传 ${files.length} 张图片`);
      return response.data.data; // 返回文件名数组
    } else {
      throw new Error(response.data.message || '批量上传失败');
    }
  } catch (error: any) {
    // console.error('批量上传失败:', error);
    ElMessage.error(error.message || '批量上传失败');
    throw error;
  }
};
